import { SelectionModel, TextModel } from "../models"
import { BaseView } from "./BaseView"

export class RenderView implements BaseView {
  // private innerPreEle?: HTMLElement | null
  private next: Promise<any> = Promise.resolve()
  constructor(
    protected textModel_: TextModel,
    protected selectionModel_: SelectionModel,
    protected viewContainer_: HTMLElement,
  ) {
    this.addEventListener()
  }

  addEventListener() {
    this.textModel_.on("text-change", this.render.bind(this))
  }

  updateDomSelection() {
    const domSelection = window.getSelection()
    if (domSelection) {
      const selectionFromModel = this.selectionModel_.getSelection()
      const anchor = selectionFromModel?.anchor
      const range = window.document.createRange()

      if (this.viewContainer_.childNodes[0]) {
        range.setStart(this.viewContainer_.childNodes[0], anchor || 0)
        range.setEnd(this.viewContainer_.childNodes[0], anchor || 0)
        domSelection.removeAllRanges()
        domSelection.addRange(range)
      }
    }
  }

  render() {
    this.viewContainer_.innerHTML = `${this.textModel_.getSpacers()}\n`
    this.next = this.next.then(() => {
      this.updateDomSelection()
    })
  }
}
export default RenderView
